import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import { removeToken } from '@/utils/auth'

// create an axios instance
// 设置基地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://ihrm-java.itheima.net',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器
service.interceptors.response.use(
  response => {
    // console.log(response.code)
    // console.log(response)
    // const res = response.data
    // if (res.success) {
    //   Message({
    //     message: res.message || 'success',
    //     type: 'success'
    //   })
    // } else {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error'
    //   })
    // }
    return response.data
  },
  error => {
    // console.dir(error.response.data.code)
    if (error.response.data.code === 10002) {
      Message({
        message: '身份认证过期',
        type: 'error'
      })
    }
    // console.log(encodeURIComponent(router.currentRoute.fullPath))
    removeToken()

    router.push('/login')

    return Promise.reject(error)
  }
)

export default service
